<template>
  <view style="padding-bottom: 180rpx;">
    <u-navbar
      :customBack="backToList"
      v-if="!$isWeixin()"
      :title="applyForm.Level == 1 ? '新增二级' : '新增门店'"
      :background="{ backgroundColor: '#ffffff' }"
      :titleBold="true"
      :is-fixed="true"
    ></u-navbar>
    <u-tabs :list="tabList" :current="tabIndex" @change="onTabChange" active-color="#FF7A23"></u-tabs>

    <view v-show="tabIndex === 0">
      <u-cell-group :border="false">
        <u-cell-item
          :border-bottom="false"
          :arrow="false"
          title="一级经销商名称"
          :value="FirstDealerInfo.Dealer_BaseInfo.Name"
        ></u-cell-item>
        <u-cell-item
          v-if="applyForm.Level == 2"
          :border-bottom="false"
          :arrow="false"
          title="二级经销商名称"
          :value="DoubleDealerInfo.Dealer_BaseInfo.Name"
        ></u-cell-item>
      </u-cell-group>

      <basic-information-form
        v-show="applyForm.Level == 1"
        :showLevel="false"
        :showBrand="true"
        :showCCType="false"
        :showChannelType="true"
        :loadCity="loadCity"
        :level="2"
        ref="basicForm"
        :metadata="DataBaseInfo"
      ></basic-information-form>

      <store-information-form
        v-show="applyForm.Level == 2"
        :showApplyReason="false"
        :loadCity="loadCity"
        ref="storeForm"
      ></store-information-form>

      <u-gap height="40" bg-color="#f5f5f5"></u-gap>

      <u-cell-group>
        <u-cell-item :arrow="false" title="申请类型" value="新增"></u-cell-item>
        <u-cell-item :arrow="false" title="申请原因">
          <u-radio-group v-model="applyForm.ApplyForReasonId">
            <view class="grid-2">
              <u-radio v-for="(item, index) in DataBaseInfo.DealerApplyFor_BaseList" :name="item.Key" :key="index">
                {{ item.Value }}
              </u-radio>
            </view>
          </u-radio-group>
        </u-cell-item>
        <u-cell-item v-if="applyForm.ApplyForReasonId == 3" :arrow="false" title="物料需求">
          <u-checkbox-group @change="onRequirementsChange">
            <view class="grid-2">
              <u-checkbox
                v-model="item.checked"
                v-for="(item, index) in DataBaseInfo.DealerMaterialRequirements_BaseList"
                :name="item.Key"
                :key="index"
              >
                {{ item.Value }}
              </u-checkbox>
            </view>
          </u-checkbox-group>
        </u-cell-item>
        <u-cell-item v-if="applyForm.ApplyForReasonId == 4" :arrow="false" title="费用需求">
          <u-checkbox-group @change="onRequirementsChange">
            <view class="grid-2">
              <u-checkbox
                v-model="item.checked"
                v-for="(item, index) in DataBaseInfo.DealerMoneyRequirements_BaseList"
                :name="item.Key"
                :key="index"
              >
                {{ item.Value }}
              </u-checkbox>
            </view>
          </u-checkbox-group>
        </u-cell-item>
        <u-cell-item v-if="applyForm.ApplyForReasonId == 5" :arrow="false" title="其他备注">
          <u-input
            v-model="applyForm.OtherNote"
            :autoHeight="true"
            type="textarea"
            inputAlign="right"
            placeholder="其他备注"
          ></u-input>
        </u-cell-item>
        <u-cell-item :arrow="false" title="申请时间">
          <u-input
            :value="$u.date(applyForm.Date * 1000, 'yyyy-mm-dd')"
            inputAlign="right"
            placeholder="请选择"
            disabled
            @click="showTimePick = true"
            type="select"
            :selectOpen="showTimePick"
          ></u-input>
          <u-picker
            :default-time="$u.date(applyForm.Date * 1000, 'yyyy-mm-dd')"
            @confirm="onTimePickerChange"
            v-model="showTimePick"
            mode="time"
            :params="{ year: true, month: true, day: true, hour: false, minute: false, second: false }"
          ></u-picker>
        </u-cell-item>
      </u-cell-group>
    </view>

    <view class="" v-show="tabIndex == 1">
      <new-store-photo v-model="applyForm.InitialStorePhoto"></new-store-photo>
    </view>

    <view class="fixed-btn u-flex">
      <u-button @tap="backToList">返回列表</u-button>
      <u-button :disabled="btnDisabled" type="warning" @tap="onSubmit">提交申请</u-button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      btnDisabled: false,
      tabIndex: 0,
      tabList: [{ name: '基本信息' }],
      showTimePick: false,
      loadCity: false,

      DataBaseInfo: {
        BusinessCategory_BaseList: [],
        CompetingGoodsBrandA_BaseList: [],
        CompetingGoodsBrandB_BaseList: [],
        CompetingGoodsBrandC_BaseList: [],
        DealerApplyFor_BaseList: [],
        DealerGrade_BaseList: [],
        DealerMaterialRequirements_BaseList: [],
        DealerMoneyRequirements_BaseList: [],
        DealerShutDown_BaseList: [],
        DealerType_BaseList: [],
        DealerAndGoReason_BaseList: []
      },

      FirstDealerInfo: {
        Dealer_BaseInfo: {
          Account: 'D02901',
          Address: '唐延路35号旺座现代城B座2701室',
          CityId: 610100,
          Created: 1460613600,
          DealerId: 114,
          Delivery_Address: '唐延路35号旺座现代城B座2701室',
          Delivery_CityId: 610100,
          Delivery_DistrictId: 659020,
          Delivery_ProvinceId: 610000,
          DistrictId: 659020,
          IsFictitious: 0,
          KeDealerNo: '01000090',
          Level: 1,
          LevelName: '一级',
          Mobile: '18629309637',
          Name: '',
          NickName: '党元斌测试',
          Parent_DealerId: 90,
          Parent_Name: '喜德瑞',
          ProvinceId: 610000,
          Referred: '西安元聚',
          State: 4,
          Telephone: ''
        },
        Dealer_OtherInfo: {
          BlessingNote: '测试1111112',
          BossBirthday: 1626192000,
          BossName: '高方明',
          BossPhone: '15007142474',
          BusinessCategory: '22,23,',
          BusinessLicenseA: 'o_1e6b7tmbk4of12fr1muqli1ofg10.jpg',
          CompetingGoodsBrandA: '5,6,8,',
          CompetingGoodsBrandB: '47,49,50,',
          CompetingGoodsBrandC: '64,65,67,70,71,',
          DealerGrade: 1,
          DealerType: 1,
          IsSign: 2,
          IsVIP: 1,
          LastYearsBDRSales: 14001,
          PeopleNum: 25,
          PercentageBDRSales: 35,
          TotalSales: 40001,
          TreatyPhoto: 'o_1ed682sou1iuf2lmc37rc31jjjd.png',
          TreatyPhotoType: 1
        },
        Dealer_RelationList: []
      },
      DoubleDealerInfo: {
        Dealer_BaseInfo: {
          Account: 'D02901',
          Address: '唐延路35号旺座现代城B座2701室',
          CityId: 610100,
          Created: 1460613600,
          DealerId: 114,
          Delivery_Address: '唐延路35号旺座现代城B座2701室',
          Delivery_CityId: 610100,
          Delivery_DistrictId: 659020,
          Delivery_ProvinceId: 610000,
          DistrictId: 659020,
          IsFictitious: 0,
          KeDealerNo: '01000090',
          Level: 1,
          LevelName: '一级',
          Mobile: '18629309637',
          Name: '',
          NickName: '党元斌测试',
          Parent_DealerId: 90,
          Parent_Name: '喜德瑞',
          ProvinceId: 610000,
          Referred: '西安元聚',
          State: 4,
          Telephone: ''
        },
        Dealer_OtherInfo: {
          BlessingNote: '测试1111112',
          BossBirthday: 1626192000,
          BossName: '高方明',
          BossPhone: '15007142474',
          BusinessCategory: '22,23,',
          BusinessLicenseA: 'o_1e6b7tmbk4of12fr1muqli1ofg10.jpg',
          CompetingGoodsBrandA: '5,6,8,',
          CompetingGoodsBrandB: '47,49,50,',
          CompetingGoodsBrandC: '64,65,67,70,71,',
          DealerGrade: 1,
          DealerType: 1,
          IsSign: 2,
          IsVIP: 1,
          LastYearsBDRSales: 14001,
          PeopleNum: 25,
          PercentageBDRSales: 35,
          TotalSales: 40001,
          TreatyPhoto: 'o_1ed682sou1iuf2lmc37rc31jjjd.png',
          TreatyPhotoType: 1
        }
      },

      applyForm: {
        DealerId: null,
        Level: 1,
        ApplyForType: 1,
        ApplyForReasonId: null,
        Date: parseInt(new Date().getTime() / 1000),
        Requirements: '',
        Remark: '',
        OtherNote: '',
        InitialStorePhoto: []
      }
    };
  },

  onLoad(options) {
    if (options.DealerId) {
      this.applyForm.DealerId = options.DealerId;
    }
    if (options.Level) {
      this.applyForm.Level = options.Level;

      if (this.applyForm.Level == 2) {
        this.tabList.push({
          name: '门店开户照片'
        });
      }
    }
    if (options.IsStore) {
      this.IsStore = options.IsStore;
    }
    this.init();

    if (this.$isWeixin()) {
      this.$setTitle(this.applyForm.Level == 1 ? '新增二级' : '新增门店');
    }
  },

  methods: {
    backToList() {
      uni.navigateBack();
    },

    onTabChange(index) {
      this.tabIndex = index;
    },

    onRequirementsChange(e) {
      this.applyForm.Requirements = e.toString();
    },

    init() {
      this.$u.api
        .newDealerInit({
          DealerId: this.applyForm.DealerId,
          Level: this.applyForm.Level
        })
        .then(res => {
          console.log(res);
          const {
            ResultCode,
            ResultMessage,
            DataBaseInfo,
            First_Dealer_OtherInfo,
            First_Dealer_BaseInfo,
            First_Dealer_RelationList,
            Double_Dealer_OtherInfo,
            Double_Dealer_BaseInfo,
            InitialStorePhoto
          } = res;
          if (ResultCode === 1) {
            this.DataBaseInfo = JSON.parse(JSON.stringify(DataBaseInfo));

            // 二级经销商 新增门店时, 二级基本信息不需要填写的;
            if (this.applyForm.Level == 2) {
              this.DataBaseInfo.BusinessCategory_BaseList.forEach(item => {
                item.checked = Double_Dealer_OtherInfo.BusinessCategory.split(',').indexOf(String(item.Key)) > -1;
              });
              this.DataBaseInfo.CompetingGoodsBrandA_BaseList.forEach(item => {
                item.checked = Double_Dealer_OtherInfo.CompetingGoodsBrandA.split(',').indexOf(String(item.Key)) > -1;
              });
              this.DataBaseInfo.CompetingGoodsBrandB_BaseList.forEach(item => {
                item.checked = Double_Dealer_OtherInfo.CompetingGoodsBrandB.split(',').indexOf(String(item.Key)) > -1;
              });
              this.DataBaseInfo.CompetingGoodsBrandC_BaseList.forEach(item => {
                item.checked = Double_Dealer_OtherInfo.CompetingGoodsBrandC.split(',').indexOf(String(item.Key)) > -1;
              });
            }

            if (this.applyForm.Level == 1) {
              this.$refs.basicForm.initForm({
                Dealer_BaseInfo: Double_Dealer_BaseInfo,
                Dealer_OtherInfo: Double_Dealer_OtherInfo
              });
            }

            if (this.applyForm.Level == 2) {
              // this.$refs.storeForm.initForm({
              // 	Dealer_BaseInfo: ,
              // 	Dealer_OtherInfo: Double_Dealer_OtherInfo,
              // })

              this.applyForm.InitialStorePhoto = InitialStorePhoto;
            }

            this.FirstDealerInfo.Dealer_BaseInfo = First_Dealer_BaseInfo;
            this.FirstDealerInfo.Dealer_OtherInfo = First_Dealer_OtherInfo;
            this.FirstDealerInfo.Dealer_RelationList = First_Dealer_RelationList;

            this.DoubleDealerInfo.Dealer_BaseInfo = Double_Dealer_BaseInfo;
            this.DoubleDealerInfo.Dealer_OtherInfo = Double_Dealer_OtherInfo;

            this.loadCity = true;
          }
        });
    },

    onTimePickerChange(e) {
      this.applyForm.Date = new Date(`${e.year}-${e.month}-${e.day}`).getTime() / 1000;
    },

    onSubmit() {
      let me = this;
      me.btnDisabled = true;
      let formParams = {};
      if (this.applyForm.Level == 1) {
        formParams = Object.assign(
          {},
          this.$refs.basicForm.form.Dealer_BaseInfo,
          this.$refs.basicForm.form.Dealer_OtherInfo
        );
      }
      if (this.applyForm.Level == 2) {
        let storeForm = this.$refs.storeForm.form;
        formParams = { ...storeForm.Dealer_BaseInfo, ...storeForm.Dealer_OtherInfo };

        formParams.ApplyForReasonId = storeForm.ApplyForReasonId;
        formParams.Requirements = storeForm.Requirements;
        formParams.OtherNote = storeForm.OtherNote;
        formParams.Remark = storeForm.Remark;
      }
      const params = Object.assign({}, formParams, this.applyForm);

      let flag = params.InitialStorePhoto.slice(0, 3).every(item => !!item.PhotoUrl);

      console.log(params);

      if (!flag) {
        this.$u.toast('必须上传门头照片、近景图、远景图');
        return false;
      }

      this.$u.api.saveNormalDealer(params).then(res => {
        const { ResultCode, ResultMessage } = res;
        if (ResultCode === 1) {
          this.$u.toast(ResultMessage);
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        } else {
          me.btnDisabled = false;
        }
      });
    }
  }
};
</script>

<style lang="scss">
.fixed-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ffffff;
  padding-bottom: 60rpx;
  padding-top: 60rpx;
}
</style>
